package com.hp.bon.sgw.service.inf;

import java.util.ArrayList;

import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.ProcessResult;
import com.hp.bon.sgw.start.SpringContext;
import com.hp.bon.sgw.threads.TaskThread;

public class ServiceChain {
	private static ServiceChain instance;

	public static ServiceChain getInstance() {
		if (instance == null) {
			instance = SpringContext.getInstance().getApplicationContext().getBean(ServiceChain.class);
		}
		return instance;
	}
	public void setPreServiceList(ArrayList<PreServiceInf> preServiceList) {
		this.preServiceList = preServiceList;
	}
	public void setPostServiceList(ArrayList<PostServiceInf> postServiceList) {
		this.postServiceList = postServiceList;
	}
	ArrayList<PreServiceInf> preServiceList;
	ArrayList<PostServiceInf> postServiceList;
	public ProcessResult doPreServices(CallParam callParam)
	{
		ProcessResult processResult = null;
		for(PreServiceInf service:preServiceList)
		{
			processResult = service.doPreService(callParam);
			if(processResult != null)
			{
				break;
			}
		}
		return processResult;
	}
	public ProcessResult doPostServices(CallParam callParam)
	{
		ProcessResult processResult = null;
		for(PostServiceInf service:postServiceList)
		{
			processResult = service.doPostService(callParam);
			if(processResult != null)
			{
				break;
			}
		}
		return processResult;
	}
	public void init(){
		for(PreServiceInf service:preServiceList)
		{
			if(service instanceof TaskThread)
			{
				((TaskThread) service).start();
			}
		}
		for(PostServiceInf service:postServiceList)
		{
			if(service instanceof TaskThread)
			{
				((TaskThread) service).start();
			}
		}
	}
	public void stop(){
		for(PreServiceInf service:preServiceList)
		{
			if(service instanceof TaskThread)
			{
				((TaskThread) service).exit();
			}
		}
		for(PostServiceInf service:postServiceList)
		{
			if(service instanceof TaskThread)
			{
				((TaskThread) service).exit();
			}
		}
	}
	
}
